const util = require('../../utils/util')
let p

Page({

	data: {
		staticDomain: util.config('staticDomain'),
		pageIndex: 0,
		photoList: [],
		tabIndex: 0,
		repairTypeName: null,
		waitOrderLoaded: false,
		acceptOrderLoaded: false,
		finishOrderLoaded: false,
		waitOrderList: [],
		acceptOrderList: [],
		finishOrderList: [],
		repairEvaluateStar: 0,
		clearForm: ''
	},

	temp: {
		repairType: null,
		repairTypes: []
	},

	onLoad: function() {
		p = this
	},

	onUnload: () => {
		util.unloadPage('repair')
	},

	onShow: () => {
		const repairType = util.globalData('repairTypeTemp')
		if (repairType) {
			p.setData({ repairTypeName: repairType.name })
			p.temp.repairType = repairType.id
		}
		const repairTypes = util.globalData('repairTypeTemp')
		if (repairTypes)
			p.temp.repairTypes = repairTypes
	},

	addPhoto: () => {
		wx.chooseImage({
			count: Math.abs(p.data.photoList.length - 3),
			sizeType: ['compressed'],
			success: function(res) {
				const {mimes, maxSize} = util.config('upload')
				for (let file of res.tempFilePaths) {
					if (file.size > maxSize.repairPhoto) {
						util.error('图片过大，无法上传，请重新选择小于10M的图片')
						return
					}
				}
				const list = p.data.photoList.concat(res.tempFilePaths)
				p.setData({
					photoList: list
				})
			}
		})
	},

	usePhoto: (e) => {
		const index = e.currentTarget.dataset.index
		wx.showActionSheet({
			itemList: ['删除'],
			success: (res) => {
				p.data.photoList.splice(index, 1)
				p.setData({
					photoList: p.data.photoList
				})
			}
		})
	},

	changePage: (e) => {
		const index = !isNaN(e) ? e : e.currentTarget.dataset.index
		wx.setNavigationBarTitle({
			title: ['报修申请', '报修进度'][index],
		})
		p.setData({
			pageIndex: index
		})
		p.loadOrder({
			success: () => {
				util.hideLoadingBox(p)
				wx.stopPullDownRefresh()
			},
			fail: (code, msg) => {
				util.hideLoadingBox(p)
				wx.stopPullDownRefresh()
				util.error('加载失败', util.errorHandler(code, msg))
			}
		})
	},

	changeTab: (e) => {
		const index = !isNaN(e) ? e : (e.detail.current || e.currentTarget.dataset.index || 0)
		p.setData({
			tabIndex: parseInt(index)
		})
		if (!e.detail || (e.detail.source != '' && e.detail.source != 'touch'))
			return
		p.loadOrder({
			success: () => {
				util.hideLoadingBox(p)
				wx.stopPullDownRefresh()
			},
			fail: (code, msg) => {
				util.hideLoadingBox(p)
				wx.stopPullDownRefresh()
				util.error('加载失败', util.errorHandler(code, msg))
			}
		})
	},

	chooseRepairType: () => {
		util.goPage('repairType')
	},

	submitRepairApply: (e) => {
		const repairType = p.temp.repairType
		if (!repairType) {
			util.error('选择报修类型', '请选择报修类型再提交申请哦')
			return
		}
		const { repairContent, repairAddress, repairContact } = e.detail.value
		if (!repairContent) {
			util.error('填写报修内容', '请填写报修内容我们才能更了解故障状态')
			return
		}
		if (!repairAddress) {
			util.error('填写维修地址', '请填写维修地址我们才能上门服务哦')
			return
		}
		if (!repairContact) {
			util.error('填写联系方式', '请填写联系方式我们才能联系到你哦')
			return
		}
		wx.showModal({
			title: '确认提交',
			content: '请确认报修信息是否完整正确，确认完毕请点击提交',
			confirmText: '提交',
			cancelText: '继续填写',
			success: (res) => {
				if(res.confirm) {
					const repairPhotoList = p.data.photoList
					util.loading('上传中')
					p.uploadRepairPhoto({
						repairPhotoList,
						success: (uploadIdList) => {
							console.log('上传成功', uploadIdList)
							util.hideLoading()
							util.loading('提交中')
							util.request({
								source: 'repair',
								method: 'post',
								uri: 'user/repair/order',
								data: {
									session: util.globalData('session'),
									repairType,
									repairContent,
									uploadIdList,
									repairAddress,
									repairContact
								},
								success: (data) => {
									util.success('提交成功')
									const { waitOrderList, repairTypeName } = p.data
									waitOrderList.unshift({
										repairId: data,
										repairType: repairTypeName,
										repairContent,
										repairPhotoCount: uploadIdList instanceof Array ? uploadIdList.length : 0,
										repairAddress,
										repairContact,
										repairCreateDate: util.timestamp()
									})
									p.setData({
										repairTypeName: null,
										photoList: [],
										clearForm: '',
										waitOrderList
									})
									p.temp.repairType = null
									p.changePage(1)
									p.changeTab(0)
								},
								fail: (code, msg) => {
									util.hideLoading()
									util.error('提交失败', util.errorHandler(code, msg))
								}
							})
						},
						fail: (code, msg) => {
							util.hideLoading()
							util.error('上传失败', util.errorHandler(code, msg))
						}
					})
				}
			}
		})
	},

	uploadRepairPhoto: (obj) => {
		let { repairPhotoList = [], success, fail, index = 0, uploadIdList = []} = obj
		if (repairPhotoList.length == 0) {
			success()
			return
		}
		util.uploadFile({
			uri: `user/repair/photo/upload`,
			name: 'image',
			file: repairPhotoList[index],
			data: {
				session: util.globalData('session')
			},
			success: (data) => {
				uploadIdList.push(data)
				if (index == repairPhotoList.length - 1) {
					success(uploadIdList)
					return
				}
				p.uploadRepairPhoto({
					repairPhotoList,
					success,
					fail,
					index: ++index,
					uploadIdList
				})
			},
			fail: (code, msg) => {
				fail(code, msg)
				return
			}
		})
	},

	loadOrder: ({ sync = false, success, fail }) => {
		let loader
		switch (p.data.tabIndex) {
			case 0:
				loader = p.loadWaitOrder
				break
			case 1:
				loader = p.loadAcceptOrder
				break
			case 2:
				loader = p.loadFinishOrder
		}
		p.setData({
			syncing: true
		})
		if (p.temp.repairTypes.length == 0) {
			util.showLoadingBox(p)
			util.request({
				source: 'repair',
				method: 'get',
				uri: 'sys/repair/type',
				data: {
					session: util.globalData('session')
				},
				success: (data) => {
					p.temp.repairTypes = data
					loader({
						success: () => {
							p.setData({
								syncing: false
							})
							success()
						},
						fail: (code, msg) => {
							p.setData({
								syncing: false
							})
							fail(code, msg)
						}
					})
				},
				fail: () => {
					util.hideLoadingBox(p)
					p.setData({
						syncing: false
					})
					fail('-1', 'network error')
				}
			})
		}
		else
			loader({
				sync,
				success: () => {
					p.setData({
						syncing: false
					})
					success()
				},
				fail: (code, msg) => {
					p.setData({
						syncing: false
					})
					fail(code, msg)
				}
			})
	},

	loadWaitOrder: ({ sync, success, fail }) => {
		if (p.data.waitOrderLoaded) {
			p.setData({
				syncing: false
			})
			return
		}
		util.showLoadingBox(p)
		util.request({
			source: 'repair',
			method: sync ? 'put' : 'get',
			uri: `user/repair/waitOrder`,
			success: (list) => {
				for (let index in list) {
					const temp = list[index].repairType.split('-')
					if(!temp[0] || !temp[1]) {
						fail('-3', 'data handle error')
						continue
					}
					list[index].repairType = p.getRepairTypeText(temp[0], temp[1])
				}
				p.setData({
					waitOrderList: list.sort((a, b) => {
						return b.repairCreateDate - a.repairCreateDate
					}),
					waitOrderLoaded: true
				})
				success()
			},
			fail
		})
	},

	loadAcceptOrder: ({ sync, success, fail }) => {
		if (p.data.acceptOrderLoaded) {
			p.setData({
				syncing: false
			})
			return
		}
		util.showLoadingBox(p)
		util.request({
			source: 'repair',
			method: sync ? 'put' : 'get',
			uri: `user/repair/acceptOrder`,
			success: (list) => {
				for (let index in list) {
					const temp = list[index].repairType.split('-')
					if (!temp[0] || !temp[1]) {
						fail('-3', 'data handle error')
						continue
					}
					list[index].repairType = p.getRepairTypeText(temp[0], temp[1])
				}
				p.setData({
					acceptOrderList: list.sort((a, b) => {
						return b.repairCreateDate - a.repairCreateDate
					}),
					acceptOrderLoaded: true
				})
				success()
			},
			fail
		})
	},

	loadFinishOrder: ({ sync, success, fail }) => {
		if (p.data.finishOrderLoaded) {
			p.setData({
				syncing: false
			})
			return
		}
		util.showLoadingBox(p)
		util.request({
			source: 'repair',
			method: sync ? 'put' : 'get',
			uri: `user/repair/finishOrder`,
			success: (list) => {
				for (let index in list) {
					const temp = list[index].repairType.split('-')
					if (!temp[0] || !temp[1]) {
						fail('-3', 'data handle error')
						continue
					}
					list[index].repairType = p.getRepairTypeText(temp[0], temp[1])
				}
				p.setData({
					finishOrderList: list.sort((a, b) => {
						return b.repairCreateDate - a.repairCreateDate
					}),
					finishOrderLoaded: true
				})
				success()
			},
			fail
		})
	},

	getRepairTypeText: (type, id) => {
		const { repairTypes } = p.temp
		let text = ''
		for (let index in repairTypes) {
			if (repairTypes[index] && repairTypes[index].i == type) {
				if (repairTypes[index].n) {
					text += `${repairTypes[index].n}-`
					if (repairTypes[index].l && repairTypes[index].l[id])
						text += repairTypes[index].l[id]
					else
						text += '未知'
				}
				else
					text += `未知-未知`
				break
			}
		}
		return text
	},

	previewPhoto: (e) => {
		const url = e.currentTarget.dataset.url
		if(!url)
			return
		wx.previewImage({
			urls: [url],
		})
	},

	openRepairEvaluate: (e) => {
		const repairId = e.currentTarget.dataset.id
		const { finishOrderList } = p.data
		for(let index in finishOrderList)
			finishOrderList[index].repairEvaluateOpened = finishOrderList[index].repairId == repairId
		p.setData({
			finishOrderList
		})
	},

	updateRepairOrderEvaluateData: (repairId, repairEvaluateStar, repairEvaluateContent) => {
		const { finishOrderList } = p.data
		for (let index in finishOrderList) {
			if (finishOrderList[index].repairId == repairId) {
				finishOrderList[index].repairEvaluateOpened = false
				finishOrderList[index].repairEvaluateStar = repairEvaluateStar
				finishOrderList[index].repairEvaluateContent = repairEvaluateContent
				break
			}
		}
		p.setData({
			finishOrderList
		})
	},

	closeAllRepairEvaluate: () => {
		const { finishOrderList } = p.data
		for (let index in finishOrderList)
			finishOrderList[index].repairEvaluateOpened = false
		p.setData({
			finishOrderList
		})
	},

	setEvaluateStar: (e) => {
		p.setData({
			repairEvaluateStar: e.currentTarget.dataset.star
		})
	},

	submitEvaluateData: (e) => {
		const repairId = e.currentTarget.dataset.id
		const { repairEvaluateStar } = p.data
		const { repairEvaluateContent } = e.detail.value
		if (repairEvaluateStar == 0) {
			util.error('系统提示', '至少需要评一颗星才能提交哦')
			return
		}
		util.loading('提交中')
		util.request({
			source: 'repair',
			method: 'post',
			uri: `user/repair/order/${repairId}/evaluate`,
			data: {
				repairEvaluateStar,
				repairEvaluateContent,
				session: util.globalData('session')
			},
			success: (data) => {
				util.hideLoading()
				util.success('提交成功')
				p.updateRepairOrderEvaluateData(repairId, repairEvaluateStar, repairEvaluateContent)
			},
			fail: (code, msg) => {
				util.hideLoading()
				util.error('提交失败', util.errorHandler(code, msg))
			}
		})
	},

	onPullDownRefresh: () => {
		const {pageIndex, tabIndex} = p.data
		if (pageIndex == 0) {
			wx.stopPullDownRefresh()
			return
		}
		switch(tabIndex) {
			case 0:
				p.setData({ waitOrderList: [], waitOrderLoaded: false })
			break
			case 1:
				p.setData({ acceptOrderList: [], acceptOrderLoaded: false })
			break
			case 2:
				p.setData({ finishOrderList: [], finishOrderLoaded: false })
		}
		p.loadOrder({
			sync: true,
			success: () => {
				util.hideLoadingBox(p)
				wx.stopPullDownRefresh()
			},
			fail: (code, msg) => {
				util.hideLoadingBox(p)
				wx.stopPullDownRefresh()
				util.error('加载失败', util.errorHandler(code, msg))
			}
		})
	},

	onShareAppMessage: () => {
		return {
			title: '报修，就找创新盒子，速报速修！',
			path: '/pages/repair/repair'
		}
	}

})